import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const Welcome = () => import(/* webpackChunkName: "Welcome" */'../views/Welcome.vue')
const Users = () => import(/* webpackChunkName: "User" */'../views/user/Users.vue')
const Roles = () => import(/* webpackChunkName: "Roles" */'../views/power/roles/Roles.vue')
const Rights = () => import(/* webpackChunkName: "Rights" */'../views/power/rights/Rights.vue')
// 商品分类
const Cate = () => import(/* webpackChunkName: "Cate" */'../views/goods/Categories.vue')
// 数据报表
const Reports = () => import(/* webpackChunkName: "Reports" */'../views/reports/Reports.vue')

const routes = [
  {
    // 重定向到login
    path: '/',
    redirect: '/login'
  },
  {
    name: 'Login',
    path: '/login',
    component: Login
  },
  {
    name: 'Home',
    path: '/home',
    component: Home,
    redirect: '/Welcome',
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: Welcome
      },
      {
        path: '/users',
        name: 'Users',
        component: Users
      },
      {
        path: '/roles',
        name: 'Roles',
        component: Roles
      },
      {
        path: '/rights',
        name: 'Rights',
        component: Rights
      },
      {
        path: '/categories',
        name: 'Cate',
        component: Cate
      },
      {
        path: '/reports',
        name: 'Reports',
        component: Reports
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// to 前往那个页面
// form 从何而来
// next 放行的函数
// 路由对象,添加beforeEach导航首卫
//   next() 放行    next('/login) 强制跳转
router.beforeEach((to, from, next) => {
  // 如果用户访问的登录页,直接放行
  if (to.path === '/login') { return next() }
  // 从sessionStorage中获取到保存的token
  const tokenStr = window.sessionStorage.getItem('token')
  // 没有token，强制跳转登录页
  if (!tokenStr) { return next('/login') }
  // 存在放行
  next()
})

export default router
